package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.WxErrorMappingUtil;
import cc.linker.steplink.crm.merchant.dao.NewMallDao;
import cc.linker.steplink.crm.merchant.dao.PublicMenuDao;
import cc.linker.steplink.crm.merchant.dao.WxDao;
import cc.linker.steplink.crm.merchant.pojo.menu.*;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;

/**
 * 公众号菜单
 * @author huhj
 */
@Slf4j
@Service
public class PublicMenuService {

    @Autowired
    private PublicMenuDao publicMenuDao;
    @Autowired
    private NewMallDao newMallDao;
    @Autowired
    private CommonsService commonsService;

    @Value("${system.scrm.defimg}")
    private String defImg;

    @Autowired
    private HttpService httpService;
    @Value("${system.scrm.wxpushurl}")
    private String wxurl;
    @Autowired
    private SystemProperties systemProperties;
    @Value("${system.scrm.defimg}")
    private String defimg;

    @Autowired
    private WxDao wxDao;
    @Autowired
    private ContentService contentService;

    @Autowired
    private SurvivalPcService survivalPcService;


    /**
     * 同步菜单
     *
     * @param orgId
     * @throws IOException
     * @throws URISyntaxException
     */
    public Map<String, Object> syncMenu(String orgId) throws IOException, URISyntaxException {
        String syncMenu = "{menu}syncMenu_" + orgId;
        Boolean globalLimitByLua = commonsService.getGlobalLimitByLua(syncMenu, 60000, 1);
        if (!globalLimitByLua) {
            throw GlobalException.build("请勿频繁同步菜单");
        }
        Map<String, Object> da = new HashMap<>();
        da.put("orgId", orgId);
        da.put("menuType", 0);
        da.put("wxMenuId", -1);
        da.put("title", "默认菜单");
        //获取公众号默认菜单
        Map<String, Object> menu = publicMenuDao.getMenu(da);
        Map<String, Object> menu1 = getMenu(orgId);
        da.put("menuData", JSON.toJSONString(menu1));
        if (null == menu) {
            publicMenuDao.addMenu(da);
        } else {
            da.put("id", menu.get("id"));
            publicMenuDao.saveMenu(da);
            survivalPcService.deleteByDefaultMenuId(orgId);
        }
        return getMenuAttribute(menu1);
    }


    public Map<String, Object> getCurrentSelfMenu(String orgId) throws IOException, URISyntaxException {
        Map<String, Object> da = new HashMap<>();
        da.put("orgId", orgId);
        da.put("menuType", 0);
        da.put("wxMenuId", -1);
        da.put("title", "默认菜单");
        //获取公众号默认菜单
        Map<String, Object> menu = publicMenuDao.getMenu(da);
        if (null == menu) {
            menu = getMenu(orgId);
            da.put("menuData", JSON.toJSONString(menu));
            publicMenuDao.addMenu(da);
            return menu;
        } else {
            menu = (Map<String, Object>) JSON.parse(menu.get("menuData").toString());
        }
        return getMenuAttribute(menu);
    }


    private Map<String, Object> getMenuAttribute(Map<String, Object> menu) {
        if(null == menu || menu.isEmpty()){
            return menu;
        }
        String[] types = {"text", "voice", "video", "news", "img"};
        List<Map<String, Object>> button = (List) menu.get("button");
        for (Map<String, Object> bu : button) {
            if (bu.containsKey("sub_button")) {
                //有二级菜单
                Map subButton = (Map) bu.get("sub_button");
                List<Map<String, Object>> subButtonList = (List) subButton.get("list");
                for (Map<String, Object> sbbBu : subButtonList) {
                    sbbBu.put("stype", "");
                    sbbBu.put("svalue", "");
                    sbbBu.put("sid", "");
                    if ("view".equals(sbbBu.get("type"))) {
                        Map<String, Object> content = publicMenuDao.getMenuContentByValue(sbbBu.get("url").toString());
                        if (null != content) {
                            sbbBu.put("sid", content.get("key"));
                        }
                    }
                    if ("click".equals(sbbBu.get("type"))) {
                        if (!sbbBu.get("key").toString().startsWith("clickPushEvent")) {
                            String[] split = sbbBu.get("key").toString().split("_");
                            if (split.length > 1) {
                                Map<String, Object> content = publicMenuDao.getMenuContent(split[1]);
                                if (null != content) {
                                    sbbBu.put("stype", content.get("type"));
                                    sbbBu.put("svalue", content.get("value"));
                                    sbbBu.put("sid", content.get("key"));
                                }
                            }
                        } else {
                            String[] split = sbbBu.get("key").toString().split("\\*");
                            if (split.length > 1) {
                                sbbBu.put("cpeId", split[1]);
                            }
                        }
                    }
                    if (Arrays.asList(types).contains(sbbBu.get("type").toString())) {
                        sbbBu.put("stype", sbbBu.get("type"));
                        if ("img".equals(sbbBu.get("type")) || "photo".equals(sbbBu.get("type"))) {
                            sbbBu.put("stype", "image");
                        }
                        if ("text".equals(sbbBu.get("type"))) {
                            sbbBu.put("svalue", sbbBu.get("value"));
                        }
                        sbbBu.put("type", "click");
                    }
                }
            } else {
                //没有二级菜单
                bu.put("stype", "");
                bu.put("svalue", "");
                bu.put("sid", "");
                if ("view".equals(bu.get("type"))) {
                    Map<String, Object> content = publicMenuDao.getMenuContentByValue(bu.get("url").toString());
                    if (null != content) {
                        bu.put("sid", content.get("key"));
                    }
                }
                if ("click".equals(bu.get("type"))) {
                    if (!bu.get("key").toString().startsWith("clickPushEvent")) {
                        String[] split = bu.get("key").toString().split("_");
                        if (split.length > 1) {
                            Map<String, Object> content = publicMenuDao.getMenuContent(split[1]);
                            if (null != content) {
                                bu.put("stype", content.get("type"));
                                bu.put("svalue", content.get("value"));
                                bu.put("sid", content.get("key"));
                            }
                        }
                    } else {
                        String[] split = bu.get("key").toString().split("\\*");
                        if (split.length > 1) {
                            bu.put("cpeId", split[1]);
                        }
                    }
                }
                if (Arrays.asList(types).contains(bu.get("type").toString())) {
                    bu.put("stype", bu.get("type"));
                    if ("img".equals(bu.get("type")) || "photo".equals(bu.get("type"))) {
                        bu.put("stype", "image");
                    }
                    if ("text".equals(bu.get("type"))) {
                        bu.put("svalue", bu.get("value"));
                    }
                    bu.put("type", "click");
                }
            }
        }
        return menu;
    }

    /**
     * 从公众号后台获取当前的默认菜单
     *
     * @param orgId
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    private Map<String, Object> getMenu(String orgId) throws IOException, URISyntaxException {
        String token = newMallDao.getTokenByOrgId(orgId);
        Map<String, String> param = new HashMap<>();
        param.put("token", token);
        param.put("action", "getCurrentSelfMenu");
        String jsonStr = JSON.toJSONString(param);

        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        String s = httpService.doPost(wxurl, jsonStr, postParam);
        if (!StringUtils.isEmpty(s)) {
            Map res = (Map) JSON.parse(s);
            if (null != res && "200".equals(res.get("errcode").toString())) {
                Map data = (Map) JSON.parse(res.get("data").toString());
                if ("0".equals(data.get("is_menu_open").toString())) {
                    return new HashMap<>();
//                    throw GlobalException.build("当前公众号没有默认菜单");
                } else {
                    return (Map<String, Object>) data.get("selfmenu_info");
                }
            }
        }
        LOGGER.error("同步公众号菜单异常:" + s);
        throw GlobalException.build("操作失败");
    }


    /**
     * @Description：验证菜单栏的参数
     * @DateTime：2020/8/26 11:01
     * @Params：
     * @Return：
     */
    private String validMenuParams(PublicMenuPo publicMenuPo, String orgCode) {
        String token = newMallDao.getTokenByOrgId(orgCode);
        if (StringUtils.isEmpty(token)) {
            throw GlobalException.build("请先绑定公众号");
        }
        if (StringUtils.isEmpty(publicMenuPo.getTitle())) {
            throw GlobalException.build("菜单标题不能为空");
        }
        if (StringUtils.isEmpty(publicMenuPo.getGroupIds())) {
            throw GlobalException.build("菜单用户分群不能为空");
        }
        if (publicMenuPo.getGroupIds().split(",").length > 5) {
            throw GlobalException.build("单个菜单最多可添加5个目标用户分群");
        }
        if (publicMenuPo.getButton() == null || publicMenuPo.getButton().size() == 0) {
            throw GlobalException.build("请先创建个性化菜单栏");
        }

        if (publicMenuDao.getDefaultPublicMenuCount().equals(0)) {
            throw GlobalException.build("创建个性化菜单前，必须先创建默认菜单！");
        }

        return token;
    }

    /**
     * @Description：获取菜单栏信息
     * @DateTime：2020/8/28 9:07
     * @Params：
     * @Return：
     */
    public PublicMenuPo getIndividualityMenuInfo(Long menuId) {
        PublicMenuPo publicMenuPo = this.publicMenuDao.getMenuModel(menuId);
        if (publicMenuPo != null) {
            publicMenuPo.setGroupList(this.publicMenuDao.getGroupListByGroupIds(publicMenuPo.getGroupIds().split(",")));
        }
        Map<String, Object> buttonMap = (Map<String, Object>) JSON.parse(publicMenuPo.getMenuData());

        List<ButtonPo> buttonList = JSONObject.parseArray(JSON.toJSONString(buttonMap.get("button")), ButtonPo.class);
        if (buttonList != null && buttonList.size() > 0) {
            for (ButtonPo buttonPo : buttonList) {
                if (buttonPo.getSub_button() != null && buttonPo.getSub_button().size() > 0) {
                    for (SubButtonPo subButtonPo : buttonPo.getSub_button()) {
                        if ("view".equals(subButtonPo.getType())) {
                            Map<String, Object> content = publicMenuDao.getMenuContentByValue(subButtonPo.getUrl());
                            if (null != content) {
                                subButtonPo.setSid(content.get("key").toString());
                            }
                        }
                        if ("click".equals(subButtonPo.getType())) {
                            if (subButtonPo.getKey().startsWith("clickPushEvent")) {
                                subButtonPo.setKey("clickPushEvent");
                            } else {
                                String[] split = subButtonPo.getKey().split("_");
                                if (split.length > 1) {
                                    Map<String, Object> content = publicMenuDao.getMenuContent(split[1]);
                                    if (null != content) {
                                        subButtonPo.setStype(content.get("type").toString());
                                        subButtonPo.setSvalue(content.get("value").toString());
                                        subButtonPo.setSid(content.get("key").toString());
                                    }
                                }
                            }
                        } else {
                            if (subButtonPo.getKey() != null) {
                                String[] split = subButtonPo.getKey().split("\\*");
                                if (split != null && split.length > 1) {
                                    subButtonPo.setCpeId(split[1]);
                                }
                            }
                        }
                    }
                } else {
                    if ("view".equals(buttonPo.getType())) {
                        Map<String, Object> content = publicMenuDao.getMenuContentByValue(buttonPo.getUrl());
                        if (null != content) {
                            buttonPo.setSid(content.get("key").toString());
                        }
                    }
                    if ("click".equals(buttonPo.getType())) {
                        if (buttonPo.getKey().startsWith("clickPushEvent")) {
                            buttonPo.setKey("clickPushEvent");
                        } else {
                            String[] split = buttonPo.getKey().split("_");
                            if (split.length > 1) {
                                Map<String, Object> content = publicMenuDao.getMenuContent(split[1]);
                                if (null != content) {
                                    buttonPo.setStype(content.get("type").toString());
                                    buttonPo.setSvalue(content.get("value").toString());
                                    buttonPo.setSid(content.get("key").toString());
                                }
                            }
                        }
                    } else {
                        if (buttonPo.getKey() != null) {
                            String[] split = buttonPo.getKey().split("\\*");
                            if (split != null && split.length > 1) {
                                buttonPo.setCpeId(split[1]);
                            }
                        }
                    }
                }
            }
        }
        publicMenuPo.setButton(buttonList);
        return publicMenuPo;
    }

    /**
     * @Description：添加个性化菜单
     * @DateTime：2020/8/24 15:18
     * @Params：
     * @Return：
     */
    public void insertIndividualityMenu(PublicMenuPo publicMenuPo, String orgCode) {
        publicMenuPo.setTitle(publicMenuPo.getTitle().trim());
        Boolean isExit = this.publicMenuDao.isExitIndividualityMenu(orgCode, publicMenuPo.getTitle(), null) > 0;
        if (isExit) {
            throw GlobalException.build("已存在相同的菜单标题");
        }
        String token = this.validMenuParams(publicMenuPo, orgCode);
        Map<String, Object> menuButton = new HashMap<>();
        menuButton.put("button", publicMenuPo.getButton());
        Map<String, Object> menuData = this.getMenuData(JSON.toJSONString(menuButton), orgCode, "");
        publicMenuPo.setMenuData(menuData.get("menuStr").toString());
        publicMenuPo.setButton((List<ButtonPo>) (((Map) JSON.parse(menuData.get("menuStr").toString())).get("button")));
        List<Integer> contentIds = (List<Integer>) menuData.get("contentIds");
        //创建微信标签
        publicMenuPo = this.createWXTag(publicMenuPo, orgCode, token);
        //创建微信个性化菜单
        publicMenuPo = this.createWXMenu(publicMenuPo, orgCode, token);
        //修改内容的菜单栏ID
        if (contentIds != null && contentIds.size() > 0) {
            this.publicMenuDao.updateContentWXMenuId(contentIds, publicMenuPo.getWxMenuId());
        }
        publicMenuPo.setMenuType(1);
        publicMenuPo.setOrgId(orgCode);
        Integer sort = this.publicMenuDao.getMaxSort(orgCode);
        publicMenuPo.setSort(sort == null ? 0 : (sort + 1));
        Integer count = this.publicMenuDao.insertIndividualityMenu(publicMenuPo);
        if (count == 0) {
            throw GlobalException.build("添加个性化菜单失败");
        }
    }

    /**
     * @Description：编辑自定义菜单栏
     * @DateTime：2020/8/26 10:54
     * @Params：
     * @Return：
     */
    public void updateIndividualityMenu(PublicMenuPo publicMenuPo, String orgCode) {

        String token = this.validMenuParams(publicMenuPo, orgCode);
        Boolean isExit = this.publicMenuDao.isExitIndividualityMenu(orgCode, publicMenuPo.getTitle(), publicMenuPo.getId()) > 0;
        if (isExit) {
            throw GlobalException.build("已存在相同的菜单标题");
        }
        PublicMenuPo oldPublicMenuPo = this.publicMenuDao.getMenuModel(publicMenuPo.getId());
        publicMenuPo.setWxTagId(oldPublicMenuPo.getWxTagId());
        publicMenuPo.setWxMenuId(oldPublicMenuPo.getWxMenuId());
        //如果老的自定义菜单标题跟新的标题不一致，需要修改微信的标签名称
        if (!oldPublicMenuPo.getTitle().equals(publicMenuPo.getTitle())) {
            Map<String, String> deleteMenuParams = new HashMap<>();
            deleteMenuParams.put("action", "updateTag");
            deleteMenuParams.put("name", publicMenuPo.getTitle());
            deleteMenuParams.put("tagId", oldPublicMenuPo.getWxTagId());
            //修改微信标签名称
            this.getWXData(deleteMenuParams, orgCode, "", token);
        }
        Map<String, Object> menuButton = new HashMap<>();
        menuButton.put("button", publicMenuPo.getButton());
        Map<String, Object> menuData = this.getMenuData(JSON.toJSONString(menuButton), orgCode, oldPublicMenuPo.getWxMenuId());
        publicMenuPo.setMenuData(menuData.get("menuStr").toString());
        publicMenuPo.setButton((List<ButtonPo>) (((Map) JSON.parse(menuData.get("menuStr").toString())).get("button")));
        List<Integer> contentIds = (List<Integer>) menuData.get("contentIds");

        //先删除菜单栏
        this.deleteWXMenu(publicMenuPo, orgCode, token);
        //规则
        publicMenuPo.setMatchrule(MatchrulePo.builder().tag_id(oldPublicMenuPo.getWxTagId()).tag_name(publicMenuPo.getTitle()).build());
        //创建微信个性化菜单
        publicMenuPo = this.createWXMenu(publicMenuPo, orgCode, token);
        //修改内容的菜单栏ID
        if (contentIds != null && contentIds.size() > 0) {
            this.publicMenuDao.updateContentWXMenuId(contentIds, publicMenuPo.getWxMenuId());
        }
        publicMenuPo.setMenuType(1);
        publicMenuPo.setOrgId(orgCode);
        publicMenuPo.setStatus(0);
        publicMenuPo.setSort(oldPublicMenuPo.getSort());

        //编辑菜单栏数据
        Integer count = this.publicMenuDao.updateIndividualityMenu(publicMenuPo);
        if (count == 0) {
            throw GlobalException.build("编辑个性化菜单失败");
        }
        survivalPcService.deleteByMenuId(publicMenuPo.getId());
    }

    /**
     * @Description：调整顺序
     * @DateTime：2020/8/27 15:03
     * @Params：
     * @Return：
     */
    public void updateIndividualityMenuSort(Long menuId, Integer moveType, String orgCode) {
        if (menuId == 0) {
            throw GlobalException.build("菜单栏ID不能为空");
        }
        PublicMenuPo publicMenuPo = this.publicMenuDao.getMenuModel(menuId);
        if (moveType == 0 && publicMenuPo.getSort().equals(0)) {
            throw GlobalException.build("无法向上移动");
        }
        this.publicMenuDao.updateMenuSort(menuId, (moveType == 0 ? -1 : 1),
                (moveType == 0 ? publicMenuPo.getSort() - 1 : publicMenuPo.getSort() + 1), moveType);
    }

    /**
     * @Description：删除个性化菜单
     * @DateTime：2020/8/25 11:08
     * @Params：
     * @Return：
     */
    public void deleteIndividualityMenuByMenuId(Long menuId, String orgCode) {
        if (menuId == null || menuId == 0) {
            throw GlobalException.build("菜单栏ID不能为空");
        }
        PublicMenuPo publicMenuPo = this.publicMenuDao.getMenuModel(menuId);
        String token = newMallDao.getTokenByOrgId(orgCode);
        this.deleteWXMenu(publicMenuPo, orgCode, token);
        this.deleteWXTag(publicMenuPo, orgCode, token);
        this.publicMenuDao.deleteMenu(menuId);
    }

    /**
     * @Description：获取菜单列表
     * @DateTime：2020/8/24 16:05
     * @Params：
     * @Return：
     */
    public List<PublicMenuPo> getIndividualityMenuList(String orgCode) {
        List<PublicMenuPo> publicMenuList = this.publicMenuDao.getIndividualityMenuList(orgCode);
        if (publicMenuList != null && publicMenuList.size() > 0) {
            for (PublicMenuPo publicMenuPo : publicMenuList) {
                publicMenuPo.setGroupList(this.publicMenuDao.getGroupListByGroupIds(publicMenuPo.getGroupIds().split(",")));
            }
        }
        return publicMenuList;
    }

    /**
     * @Description：删除微信菜单栏
     * @DateTime：2020/8/25 14:48
     * @Params：
     * @Return：
     */
    private void deleteWXMenu(PublicMenuPo publicMenuPo, String orgCode, String token) {

        if (!StringUtils.isEmpty(publicMenuPo.getWxMenuId())) {
            Map<String, String> deleteMenuParams = new HashMap<>();
            deleteMenuParams.put("action", "delConditionalMenu");
            deleteMenuParams.put("menuId", publicMenuPo.getWxMenuId());
            deleteMenuParams.put("token", token);
            String s = "";
            try {
                s = httpService.doPost(wxurl, JSON.toJSONString(deleteMenuParams), ContentConstant.JSON_HEADER);
                LOGGER.info("createWXTag---------删除微信自定义菜单返回值-----" + s);
            } catch (Exception ex) {
                LOGGER.error("createWXTag---------删除微信自定义菜单失败，参数" + JSON.toJSONString(deleteMenuParams));
            }
            if (!StringUtils.isEmpty(s)) {
                Map res = (Map) JSON.parse(s);
                if (null != res && "500".equals(res.get("errcode").toString())) {
                    if (res.get("data") != null) {
                        Map errorResult = (Map) JSON.parse(res.get("data").toString());
                        if (!errorResult.get("errcode").toString().equals("65301")) {
                            String msg = WxErrorMappingUtil.getWxErrorMsg(errorResult.get("errcode").toString());
                            if (StringUtils.isEmpty(msg)) {
                                throw GlobalException.build("删除自定义菜单失败");
                            } else {
                                throw GlobalException.build(msg);
                            }
                        }
                    } else {
                        throw GlobalException.build(res.get("msg").toString());
                    }
                }
            } else {
                throw GlobalException.build("删除自定义菜单失败");
            }
        }
    }

    /**
     * @Description：删除微信标签
     * @DateTime：2020/8/25 14:48
     * @Params：
     * @Return：
     */
    private void deleteWXTag(PublicMenuPo publicMenuPo, String orgCode, String token) {
        Map<String, String> deleteTagParams = new HashMap<>();
        deleteTagParams.put("action", "deleteTag");
        deleteTagParams.put("tagId", publicMenuPo.getWxTagId());
        try {
            this.getWXData(deleteTagParams, orgCode, "", token);

        } catch (Exception ex) {
            LOGGER.error("deleteWXTag-----删除微信标签", ex);
            throw GlobalException.build("保存个性化菜单失败");
        }
    }

    /**
     * @Description：创建微信标签
     * @DateTime：2020/8/25 14:50
     * @Params：
     * @Return：
     */
    private PublicMenuPo createWXTag(PublicMenuPo publicMenuPo, String orgCode, String token) {
        Map<String, String> tagParams = new HashMap<>();
        tagParams.put("action", "createTag");
        tagParams.put("name", publicMenuPo.getTitle());
        tagParams.put("token", token);
        String s = "";
        try {
            s = httpService.doPost(wxurl, JSON.toJSONString(tagParams), ContentConstant.JSON_HEADER);
            LOGGER.info("createWXTag---------创建微信标签返回值-----" + s);
        } catch (Exception ex) {
            LOGGER.error("createWXTag---------创建微信标签失败，参数" + JSON.toJSONString(tagParams));
        }
        if (!StringUtils.isEmpty(s)) {
            Map res = (Map) JSON.parse(s);
            if (null != res && "200".equals(res.get("errcode").toString())) {
                if (res.get("data") != null) {
                    Map tagResult = (Map) JSON.parse(res.get("data").toString());
                    if (tagResult != null && tagResult.get("tag") != null) {
                        tagResult = (Map) tagResult.get("tag");
                        MatchrulePo matchrulePo = MatchrulePo.builder().tag_id(tagResult.get("id").toString())
                                .tag_name(tagResult.get("name").toString())
                                .build();
                        publicMenuPo.setWxTagId(tagResult.get("id").toString());
                        publicMenuPo.setMatchrule(matchrulePo);
                    }
                } else {
                    throw GlobalException.build("保存个性化菜单失败");
                }
            } else {
                if (res.get("data") != null) {
                    Map errorResult = (Map) JSON.parse(res.get("data").toString());
                    String msg = WxErrorMappingUtil.getWxErrorMsg(errorResult.get("errcode").toString());
                    if (StringUtils.isEmpty(msg)) {
                        throw GlobalException.build("保存个性化菜单失败");
                    } else {
                        throw GlobalException.build(msg);
                    }
                } else {
                    throw GlobalException.build(res.get("msg").toString());
                }
            }
        } else {
            throw GlobalException.build("保存个性化菜单失败");
        }
        return publicMenuPo;
    }


    /**
     * @Description：创建微信个性化菜单
     * @DateTime：2020/8/25 14:54
     * @Params：
     * @Return：
     */
    private PublicMenuPo createWXMenu(PublicMenuPo publicMenuPo, String orgCode, String token) {
        String msg = "";
        Map<String, Object> setMenuParam = new HashMap<>();
        setMenuParam.put("button", publicMenuPo.getButton());
        setMenuParam.put("matchrule", publicMenuPo.getMatchrule());
        //组装数据
        Map<String, String> params = new HashMap<>();
        params.put("action", "setMenu");
        params.put("menuList", JSON.toJSONString(setMenuParam));
        params.put("token", token);
        String s = "";
        try {
            s = httpService.doPost(wxurl, JSON.toJSONString(params), ContentConstant.JSON_HEADER);
            LOGGER.info("createWXMenu---------创建微信个性化菜单微信返回数据-----" + s);
        } catch (Exception ex) {
            LOGGER.error("createWXMenu---------创建微信个性化菜单失败，参数" + JSON.toJSONString(publicMenuPo));
        }
        if (!StringUtils.isEmpty(s)) {
            Map res = (Map) JSON.parse(s);
            if (null != res && "200".equals(res.get("errcode").toString())) {
                if (res.get("data") != null) {
                    Map resultMenu = (Map) JSON.parse(res.get("data").toString());
                    publicMenuPo.setWxMenuId(resultMenu.get("menuid").toString());
                } else {
                    msg = "保存个性化菜单失败";
                }
            } else {
                if (res.get("data") != null) {
                    Map errorResult = (Map) JSON.parse(res.get("data").toString());
                    msg = WxErrorMappingUtil.getWxErrorMsg(errorResult.get("errcode").toString());
                    if (StringUtils.isEmpty(msg)) {
                        msg = "保存个性化菜单失败";
                    }
                } else {
                    msg = res.get("msg").toString();
                }
            }
        } else {
            msg = "保存个性化菜单失败";
        }
        if (!StringUtils.isEmpty(msg)) {
            this.deleteWXTag(publicMenuPo, orgCode, token);
            throw GlobalException.build(msg);
        }
        return publicMenuPo;
    }

    /**
     * @Description：获取微信数据
     * @DateTime：2020/8/24 17:21
     * @Params：
     * @Return：
     */
    private Object getWXData(Map<String, String> params, String orgId, String resultParam, String token) {
        String msg = "调用微信获取数据失败";
        if (StringUtils.isEmpty(token)) {
            token = newMallDao.getTokenByOrgId(orgId);
        }
        params.put("token", token);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        String s = "";
        try {
            s = httpService.doPost(wxurl, JSON.toJSONString(params), postParam);
        } catch (Exception ex) {
            LOGGER.error("调用微信接口异常-----params:" + params, ex);
            throw GlobalException.build(msg);
        }
        LOGGER.info("getWXData-------params：" + JSON.toJSONString(params) + "-------reslt:", s);
        if (!StringUtils.isEmpty(s)) {
            Map res = (Map) JSON.parse(s);
            if (null != res && "200".equals(res.get("errcode").toString())) {
                if (res.get("data") != null) {
                    if (!res.get("data").toString().equals("ok")) {
                        Map data = (Map) JSON.parse(res.get("data").toString());
                        return StringUtils.isEmpty(resultParam) ? data : data.get(resultParam);
                    }
                    return null;
                } else {
                    return null;
                }
            } else {
                if (res.get("data") != null) {
                    Map errorResult = (Map) JSON.parse(res.get("data").toString());
                    msg = WxErrorMappingUtil.getWxErrorMsg(errorResult.get("errcode").toString());
                    if (StringUtils.isEmpty(msg)) {
                        msg = "调用微信获取数据失败";
                    }
                } else {
                    msg = res.get("msg").toString();
                }
            }
        }
        throw GlobalException.build(msg);
    }

    /**
     * 发布默认菜单
     *
     * @param param
     * @throws IOException
     * @throws URISyntaxException
     */
    public void publishMenu(Map<String, Object> param) throws IOException, URISyntaxException {
        String orgId = (String) param.get("orgId");
        param.put("action", "menuCreate");
        param.put("token", newMallDao.getTokenByOrgId(orgId));
        Map<String, Object> menuData = getMenuData(JSON.toJSONString(param.get("data")), orgId, "-1");
        param.put("data", menuData.get("menuStr"));
        String jsonStr = JSON.toJSONString(param, SerializerFeature.WriteMapNullValue);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        String s = httpService.doPost(wxurl, jsonStr, postParam);
        if (!StringUtils.isEmpty(s)) {
            Map res = (Map) JSON.parse(s);
            if (null != res && "200".equals(res.get("errcode").toString())) {
                Map<String, Object> da = new HashMap<>();
                da.put("orgId", orgId);
                da.put("menuType", 0);
                da.put("menuData", JSON.toJSONString(getMenu(orgId)));
                publicMenuDao.saveDefaultMenu(da);
                survivalPcService.deleteByDefaultMenuId(orgId);
                return;
            } else {
                throw GlobalException.build(res.get("msg").toString());
            }
        }
        LOGGER.error("发布公众号菜单异常:", s);
        throw GlobalException.build("操作失败");
    }

    /**
     * 点击菜单发送消息
     *
     * @param paramStr
     */
    public void sendMessage(String paramStr) {

        LOGGER.info("菜单事件推送到mq3:" + paramStr);
        Map param = (Map) JSON.parse(paramStr);
        String eventKey = param.get("eventKey").toString();
        //点击推事件，不发消息
        if ("clickPushEvent".equals(eventKey)) {
            return;
        }
        String token = (String) param.get("token");
        String openId = (String) param.get("openId");
        String[] eventArr = eventKey.split("_");
        if (eventArr.length < 2) {
            return;
        }
        String eventType = eventArr[0];
        String eventId = eventArr[1];
        Map<String, Object> menuContent = publicMenuDao.getMenuContent(eventId);
        if (null == menuContent) {
            return;
        }

        LOGGER.info("菜单事件推送到mq4:" + JSON.toJSONString(menuContent));

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("openid", openId);
        switch (eventType) {
            case "image":
                result.put("type", "image");
                result.put("action", "activeReply");
                result.put("val", menuContent.get("value"));
                break;
            case "voice":
                result.put("type", "voice");
                result.put("action", "activeReply");
                result.put("val", menuContent.get("value"));
                break;
            case "video":
                Map videoMap = this.getArticleById(menuContent.get("key").toString());
                result.put("type", "video");
                result.put("action", "activeReply");
                result.put("val", menuContent.get("value"));
                result.put("title", videoMap.get("title"));
                result.put("desc", videoMap.get("desc"));
//                result.put("thumb", videoMap.get("image"));
                break;
            case "news":
                Map articleMap = this.getNewsArticleById(menuContent.get("value").toString());
                result.put("url", articleMap.get("shortUrl"));
                result.put("title", articleMap.get("title"));
                result.put("image", articleMap.get("image"));
                if (StringUtils.isEmpty(articleMap.get("desc"))) {
                    result.put("desc", " ");
                } else {
                    result.put("desc", articleMap.get("desc"));
                }
                result.put("action", "replayNews");
                break;
            case "text":
                result.put("type", "text");
                result.put("action", "activeReply");
                result.put("val", menuContent.get("value"));
                break;
            default:
                break;
        }
        try {
            LOGGER.info("调用矩阵发送push====>参数为==》" + JSON.toJSONString(result));
            String s = httpService.doPost(systemProperties.getWxpushurl(), JSON.toJSONString(result));
            LOGGER.info("调用矩阵发送push====>结果==》" + s);
        } catch (Exception e) {
            LOGGER.error("矩阵调用异常");
        }
    }


    public Map getArticleById(String articleId) {
        Map map = new HashMap();
        String title = " ";
        String image = defImg;
        String desc = " ";
        try {
            Map materialDetail = contentService.getMaterialDetail(articleId);
            if (null != materialDetail) {
                if (!StringUtils.isEmpty(materialDetail.get("Name"))) {
                    title = materialDetail.get("Name").toString();
                }
                if (null != materialDetail.get("CoverList")) {
                    List<String> coverList = (List) materialDetail.get("CoverList");
                    if (coverList.size() > 0) {
                        image = coverList.get(0);
                    } else {
                        image = defImg;
                    }
                }
                if (!StringUtils.isEmpty(materialDetail.get("Note"))) {
                    desc = materialDetail.get("Note").toString();
                }
            }
            map.put("title", title);
            map.put("image", image);
            map.put("desc", desc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 根据文章id获取详情
     * getNewsArticleById
     *
     * @param articleId
     * @return
     */
    public Map getNewsArticleById(String articleId) {
        Map map = new HashMap();
        String title = " ";
        String image = defImg;
        String desc = " ";
        String shortUrl = " ";
        try {
            String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_DETAIL;
            Map<String, Object> param = new HashMap<>();
            param.put("newsId", articleId);
            JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
            String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
            if (null != postres) {
                Map res = (Map) JSON.parse(postres);
                if(null == res){
                    throw GlobalException.build("暂无文章数据");
                }
                if ("200".equals(res.get("code").toString())) {
                    if (!res.containsKey("data") || res.get("data") == null) {
                        throw GlobalException.build("暂无文章数据");
                    }
                    if (res.get("data") != null) {
                        if (((Map) res.get("data")).get("newsName") != null) {
                            title = ((Map) res.get("data")).get("newsName").toString();
                        }
                        if (((Map) res.get("data")).get("newsCover") != null) {
                            List nc = (List) ((Map) res.get("data")).get("newsCover");
                            if (null == nc || nc.size() == 0) {
                                image = defimg;
                            } else {
                                image = nc.get(0).toString();
                            }
                        }
                        if (((Map) res.get("data")).get("newsSummary") != null) {
                            desc = ((Map) res.get("data")).get("newsSummary").toString();
                        }
                        if (((Map) res.get("data")).get("shortUrl") != null) {
                            shortUrl = ((Map) res.get("data")).get("shortUrl").toString();
                        }
                        map.put("title", title);
                        map.put("image", image);
                        map.put("desc", desc);
                        map.put("shortUrl", shortUrl);
                    }
                } else {
                    throw GlobalException.build("请求失败");
                }
            } else {
                throw GlobalException.build("请求失败");
            }
        } catch (Exception ex) {
            LOGGER.error("getNewsArticleById--------error", ex);
            throw GlobalException.build("请求失败");
        }
        return map;
    }

    public void allMenuDelete(String orgId) throws IOException, URISyntaxException {
        Map<String, Object> param = new HashMap<>();
        param.put("token", newMallDao.getTokenByOrgId(orgId));
        param.put("action", "allMenuDelete");
        String jsonStr = JSON.toJSONString(param, SerializerFeature.WriteMapNullValue);
        Map<String, String> postParam = new HashMap<>();
        postParam.put("Content-Type", "application/json;charset=UTF-8");
        String s = httpService.doPost(wxurl, jsonStr, postParam);
        if (!StringUtils.isEmpty(s)) {
            Map res = (Map) JSON.parse(s);
            if (null != res && "200".equals(res.get("errcode").toString())) {
                publicMenuDao.delAllMenu(orgId);
                publicMenuDao.delMenuContent("-1", orgId);
                return;
            }
        }
        LOGGER.error("删除公众号菜单异常:", s);
        throw GlobalException.build("操作失败");
    }


    /**
     * @param menu     菜单的json字符串
     * @param orgId    机构ID
     * @param wxMenuId 菜单Id，新增的时候传null
     * @return
     */
    private Map<String, Object> getMenuData(String menu, String orgId, String wxMenuId) {
        if (!StringUtils.isEmpty(wxMenuId)) {
            publicMenuDao.delMenuContent(wxMenuId, orgId);
        }
        Map menuData = (Map) JSON.parse(menu);
        List<Map<String, Object>> button = (List) menuData.get("button");
        List<Integer> cIds = new ArrayList<>();
        for (Map<String, Object> bu : button) {
            if (bu.containsKey("sub_button")) {
                //有二级菜单
                List<Map<String, Object>> subButton = (List) bu.get("sub_button");
                if (subButton.size() > 0) {
                    for (Map<String, Object> sbbBu : subButton) {
                        if ("view".equals(sbbBu.get("type")) && !StringUtils.isEmpty(sbbBu.get("sid"))) {
                            Map<String, Object> content = new HashMap<>();
                            content.put("type", "view");
                            content.put("value", sbbBu.get("url"));
                            content.put("key", sbbBu.get("sid"));
                            content.put("orgId", orgId);
                            content.put("wxMenuId", wxMenuId);
                            publicMenuDao.addMenuContent(content);
                        }
                        if ("click".equals(sbbBu.get("type"))) {
                            if (!StringUtils.isEmpty(sbbBu.get("key")) && "clickPushEvent".equals(sbbBu.get("key").toString())) {
                                if (StringUtils.isEmpty(sbbBu.get("cpeId"))) {
                                    sbbBu.put("key", "clickPushEvent*" + UUID.randomUUID());
                                } else {
                                    sbbBu.put("key", "clickPushEvent*" + sbbBu.get("cpeId").toString());
                                }
//                                sbbBu.put("key","clickPushEvent*"+ UUID.randomUUID());
                            } else {
                                Map<String, Object> content = new HashMap<>();
                                content.put("type", sbbBu.get("stype"));
                                content.put("value", sbbBu.get("svalue"));
                                content.put("key", StringUtils.isEmpty(sbbBu.get("sid")) ? " " : sbbBu.get("sid"));
                                content.put("orgId", orgId);
                                content.put("wxMenuId", wxMenuId);
                                publicMenuDao.addMenuContent(content);
                                cIds.add(Integer.valueOf(content.get("id").toString()));
                                String mkey = sbbBu.get("stype") + "_" + content.get("id");
                                sbbBu.put("key", mkey);
                            }
                        }
                    }
                } else {
                    //没有二级菜单
                    if ("view".equals(bu.get("type")) && !StringUtils.isEmpty(bu.get("sid"))) {
                        Map<String, Object> content = new HashMap<>();
                        content.put("type", "view");
                        content.put("value", bu.get("url"));
                        content.put("key", bu.get("sid"));
                        content.put("orgId", orgId);
                        content.put("wxMenuId", wxMenuId);
                        publicMenuDao.addMenuContent(content);
                    }
                    if ("click".equals(bu.get("type"))) {
                        if (!StringUtils.isEmpty(bu.get("key")) && "clickPushEvent".equals(bu.get("key").toString())) {
                            if (StringUtils.isEmpty(bu.get("cpeId"))) {
                                bu.put("key", "clickPushEvent*" + UUID.randomUUID());
                            } else {
                                bu.put("key", "clickPushEvent*" + bu.get("cpeId").toString());
                            }
//                            bu.put("key","clickPushEvent*"+ UUID.randomUUID());
                        } else {
                            Map<String, Object> content = new HashMap<>();
                            content.put("type", bu.get("stype"));
                            content.put("value", bu.get("svalue"));
                            content.put("key", StringUtils.isEmpty(bu.get("sid")) ? "" : bu.get("sid"));
                            content.put("orgId", orgId);
                            content.put("wxMenuId", wxMenuId);
                            publicMenuDao.addMenuContent(content);
                            cIds.add(Integer.valueOf(content.get("id").toString()));
                            String mkey = bu.get("stype") + "_" + content.get("id");
                            bu.put("key", mkey);
                        }
                    }
                }
            } else {
                //没有二级菜单
                if ("view".equals(bu.get("type")) && !StringUtils.isEmpty(bu.get("sid"))) {
                    Map<String, Object> content = new HashMap<>();
                    content.put("type", "view");
                    content.put("value", bu.get("url"));
                    content.put("key", bu.get("sid"));
                    content.put("orgId", orgId);
                    content.put("wxMenuId", wxMenuId);
                    publicMenuDao.addMenuContent(content);
                }
                if ("click".equals(bu.get("type"))) {
                    if (!StringUtils.isEmpty(bu.get("key")) && "clickPushEvent".equals(bu.get("key").toString())) {
                        if (StringUtils.isEmpty(bu.get("cpeId"))) {
                            bu.put("key", "clickPushEvent*" + UUID.randomUUID());
                        } else {
                            bu.put("key", "clickPushEvent*" + bu.get("cpeId").toString());
                        }
//                        bu.put("key", "clickPushEvent*" + UUID.randomUUID());
                    } else {
                        Map<String, Object> content = new HashMap<>();
                        content.put("type", bu.get("stype"));
                        content.put("value", bu.get("svalue"));
                        content.put("key", StringUtils.isEmpty(bu.get("sid")) ? "" : bu.get("sid"));
                        content.put("orgId", orgId);
                        content.put("wxMenuId", wxMenuId);
                        publicMenuDao.addMenuContent(content);
                        cIds.add(Integer.valueOf(content.get("id").toString()));
                        String mkey = bu.get("stype") + "_" + content.get("id");
                        bu.put("key", mkey);
                    }
                }
            }
        }
        Map<String, Object> da = new HashMap<>(2);
        da.put("menuStr", JSON.toJSONString(menuData));
        da.put("contentIds", cIds);
        return da;
    }

    public boolean getPublicVerify(String orgId) throws IOException, URISyntaxException {

        String publicVerify = publicMenuDao.getPublicVerify(orgId);
        return "0".equals(publicVerify);

//        Map<String,Object> param = new HashMap<>();
//        param.put("token",newMallDao.getTokenByOrgId(orgId));
//        param.put("action","getPublicVerify");
//        String jsonStr = JSON.toJSONString(param, SerializerFeature.WriteMapNullValue);
//        Map<String, String> postParam = new HashMap<>();
//        postParam.put("Content-Type", "application/json;charset=UTF-8");
//        String s = httpService.doPost(wxurl, jsonStr, postParam);
//        if(!StringUtils.isEmpty(s)){
//            Map res = (Map)JSON.parse(s);
//            if(null!=res && "200".equals(res.get("errcode").toString())){
//                Map resData = (Map)res.get("data");
//                return "0".equals(resData.get("verify_type").toString());
//            }
//        }
//        return false;
    }

    //region 下发计算任务
//    /**
//    * @Description：分群改变的时候触发
//    * @DateTime：2020/8/27 13:55
//    * @Params：
//    * @Return：
//    */
//    @Async
//    public void groupChange(String orgCode,List<String> groupIds) {
//        Integer count = this.publicMenuDao.getGroupIsExit(groupIds, orgCode);
//        LOGGER.info("groupChange----------count:" + count);
//        if (count > 0) {
//            this.calculateGroupCustomerTag(orgCode);
//        }
//    }
//
//    /**
//    * @Description：分群任务执行变更后
//    * @DateTime：2020/8/27 14:29
//    * @Params：
//    * @Return：
//    */
//    @Async
//    public void groupTaskChange() {
//        List<Map<String, Object>> tokenList = wxDao.getWxPublistList();
//        for (Map<String, Object> tokenMap : tokenList) {
//            this.runCalculateGroupCustomerTag(tokenMap.get("orgId").toString());
//        }
//        //执行用户打标签的事件
//        this.runMakeCustomerTag();
//    }
//
//    /**
//    * @Description 添加计算任务到队列
//    * @DateTime：2020/8/27 14:34
//    * @Params：
//    * @Return：
//    */
//    public void calculateGroupCustomerTag(String orgCode) {
//        Long count = stringRedisTemplate.opsForList().size(CALCULATE_CUSTOMER_TAG + orgCode);
//        if (count == 0) {
//            stringRedisTemplate.opsForList().rightPush(CALCULATE_CUSTOMER_TAG + orgCode, orgCode);
//        }
//    }
    //endregion


    /**
     * @Description：下发计算标签和打标签
     * @DateTime：2020/8/27 16:36
     * @Params：
     * @Return：
     */
    @Async
    public void runCustomerTask() {
        List<Map<String, Object>> tokenList = wxDao.getWxPublistList();
        this.runCalculateGroupCustomerTag(tokenList);
        this.runMakeCustomerTag(tokenList);
    }

    /**
     * @Description：计算分群的优先级打上标签，并给分群下的用户打标签
     * @DateTime：2020/8/26 23:15
     * @Params：
     * @Return：
     */
    public void runCalculateGroupCustomerTag(List<Map<String, Object>> tokenList) {
        //删除备份表中的数据
        this.publicMenuDao.removeOldCustomerTag();
        for (Map<String, Object> tokenMap : tokenList) {
            List<PublicMenuPo> publicMenuList = this.publicMenuDao.getIndividualityList(tokenMap.get("orgId").toString());
            if (publicMenuList.size() > 0) {
                List<String> wxTagIds = new ArrayList<>();
                for (PublicMenuPo publicMenuPo : publicMenuList) {
                    if (!StringUtils.isEmpty(publicMenuPo.getWxTagId())) {
                        wxTagIds.add(publicMenuPo.getWxTagId());
                    }
                }
                //先把老的用户标签备份
                this.publicMenuDao.inesrtCustomerTagOldData(wxTagIds);
                //删除原先的用户标签
                this.publicMenuDao.removeCustomerTag(wxTagIds);

                List<String> groupIds = new ArrayList<>();
                for (PublicMenuPo publicMenuPo : publicMenuList) {
                    List<String> nGroupIds = Arrays.asList(publicMenuPo.getGroupIds().split(","));
                    for (String nGroupId : nGroupIds) {
                        Boolean isExit = false;
                        for (String groupId : groupIds) {
                            if (groupId.equals(nGroupId)) {
                                isExit = true;
                            }
                        }
                        if (!isExit) {
                            groupIds.add(nGroupId);
                        }
                    }
                }

                List<GroupTagPo> groupRankList = new ArrayList<>();
                //给分群打上微信标签ID
                for (String groupId : groupIds) {
                    for (PublicMenuPo publicMenuPo : publicMenuList) {
                        if (publicMenuPo.getGroupIds().indexOf(groupId) > -1) {
                            boolean isExit = false;
                            for (GroupTagPo groupTagPo : groupRankList) {
                                if (groupTagPo.getGroupId().equals(groupId)) {
                                    isExit = true;
                                }
                            }
                            if (!isExit) {
                                groupRankList.add(GroupTagPo.builder().groupId(groupId).wxTagId(publicMenuPo.getWxTagId()).build());
                            }
                        }
                    }
                }
                int i = 0;
                //遍历分群排行，给分群下的用户打上分群上的标签
                for (GroupTagPo groupTagPo : groupRankList) {
                    //需要排除的分组ID列表
                    List<String> excludeGroupIds = new ArrayList<>();
                    for (int j = 0; j < i; j++) {
                        excludeGroupIds.add(groupRankList.get(j).getGroupId());
                    }
                    boolean isData = true;
                    int num = 0;
                    while (isData) {
                        List<String> customerIds = new ArrayList<>();
                        List<TagCustomerPo> customerList = this.publicMenuDao.getCustomerListByGroupId(num * 1000, 1000, groupTagPo.getGroupId(), excludeGroupIds);
                        if (customerList != null && customerList.size() > 0) {
                            if (customerList.size() < 1000) {
                                isData = false;
                            }
                            for (TagCustomerPo tagCustomerPo : customerList) {
                                tagCustomerPo.setWxTagId(groupTagPo.getWxTagId());
                            }
//                        this.publicMenuDao.removeInexistenceCustomerTag(groupTagPo.getGroupId(),groupTagPo.getWxTagId());
                            this.publicMenuDao.saveTagCustomerList(customerList);
                        } else {
                            isData = false;
                        }
                    }
                    i++;
                }
            }
        }
    }

    /**
     * @Description：执行调用微信给用户打上标签
     * @DateTime：2020/8/26 22:39
     * @Params：
     * @Return：
     */
    public void runMakeCustomerTag(List<Map<String, Object>> tokenList) {
        //遍历所有公众号
        for (Map<String, Object> tokenMap : tokenList) {
            List<PublicMenuPo> publicMenuList = this.publicMenuDao.getIndividualityList(tokenMap.get("orgId").toString());
            if (publicMenuList.size() > 0) {
                //遍历机构下的所有自定义菜单
                for (PublicMenuPo publicMenuPo : publicMenuList) {
                    boolean isData = true;
                    int num = 0;
                    while (isData) {
                        List<TagCustomerPo> removeCustomerList = this.publicMenuDao.getCustomerListByRemoveTag(num * 50, 50, publicMenuPo.getWxTagId());
                        if (removeCustomerList == null || removeCustomerList.size() < 50) {
                            isData = false;
                        }
                        if (removeCustomerList.size() > 0) {
                            List<String> removeCustomerTagList = new ArrayList<>();
                            for (TagCustomerPo tagCustomerPo : removeCustomerList) {
                                removeCustomerTagList.add(tagCustomerPo.getWxOpenId());
                            }
                            //先执行删除用户的指定标签
                            this.doCustomerTagWx("batchunTag", removeCustomerTagList, tokenMap.get("token").toString(), publicMenuPo.getWxTagId());
                        }
                        num++;
                    }
                    isData = true;
                    num = 0;
                    while (isData) {
                        //获取指定微信标签下需要更改标签的用户列表
                        List<TagCustomerPo> tagCustomerList = this.publicMenuDao.getCustomerListByWxTagId(num * 50, 50, publicMenuPo.getWxTagId());
                        if (tagCustomerList == null || tagCustomerList.size() < 50) {
                            isData = false;
                        }
                        if (tagCustomerList.size() > 0) {
                            List<String> addCustomerTagList = new ArrayList<>();
                            for (TagCustomerPo tagCustomerPo : tagCustomerList) {
                                addCustomerTagList.add(tagCustomerPo.getWxOpenId());
                            }
                            //执行给用户打上标签
                            this.doCustomerTagWx("batchTagging", addCustomerTagList, tokenMap.get("token").toString(), publicMenuPo.getWxTagId());
                        }
                        num++;
                    }
                }
            }
        }
    }

    /**
     * @Description：执行微信删除或打上标签
     * @DateTime：2020/8/27 11:29
     * @Params：
     * @Return：
     */
    private void doCustomerTagWx(String active, List<String> openIds, String token, String wxTagId) {
        if (openIds != null && openIds.size() > 0) {
            //region 请求微信给用户批量添加标签
            Map<String, String> customerParam = new HashMap<>();
            customerParam.put("action", active);
            customerParam.put("openidList", String.join(",", openIds));
            customerParam.put("tagId", wxTagId);
            customerParam.put("token", token);
            Map<String, String> postParam = new HashMap<>();
            postParam.put("Content-Type", "application/json;charset=UTF-8");
            try {
                String s = httpService.doPost(wxurl, JSON.toJSONString(customerParam), postParam);
                if (!StringUtils.isEmpty(s)) {
                    Map res = (Map) JSON.parse(s);
                    if (null != res && !"200".equals(res.get("errcode").toString())) {
                        LOGGER.error("doCustomerTagWx-------error:" + s + "，params=" + JSON.toJSONString(customerParam));
                    }
                }
            } catch (Exception ex) {
                LOGGER.error("doCustomerTagWx-------error:" + ex.toString());
            }
            //endregion
        } else {
            LOGGER.warn("doCustomerTagWx-----warn:openIds为空");
        }
    }

    public Map<String, Object> getSyncStatus(String orgId) {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("menuType", 0);
        param.put("wxMenuId", -1);
        param.put("title", "默认菜单");
        //获取公众号默认菜单
        Map<String, Object> menu = publicMenuDao.getMenu(param);
        if (null != menu) {
            data.put("createTime", menu.get("createTime"));
            data.put("status", 1);
        } else {
            data.put("status", 0);
            data.put("createTime", "");
        }
        return data;
    }

    public Map<String, Object> getPublicInfo(String orgId) {
        Map<String, Object> publicInfo = publicMenuDao.getPublicInfo(orgId);
        if (null == publicInfo) {
            throw GlobalException.build("公众号未绑定");
        }
        return publicInfo;
    }

    /**
     * @Description：判断资源是否存在
     * @DateTime：2020/9/4 16:27
     * @Params：
     * @Return：
     */
    public List<ResourcePo> vaildResourceExit(ResourceListPo params) {
        for (ResourcePo resPo : params.getResList()) {
            if (resPo.getType().equals(0)) {
                resPo.setIsExit(this.contentService.getResourceIsExit(resPo.getResId()));
            } else {
                resPo.setIsExit(this.getNewsIsExit(resPo.getResId()));
            }
        }
        return params.getResList();
    }

    /**
     * @Description：获取内容库图文是否存在
     * @DateTime：2020/9/4 16:23
     * @Params：
     * @Return：
     */
    private Boolean getNewsIsExit(String articleId) {
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_DETAIL;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("newsId", articleId);
        try {
            String postres = httpService.doPost(url, JSON.toJSONString(param), ContentConstant.JSON_HEADER);
            LOGGER.info("getarticledetail===result===" + postres);
            if (null != postres) {
                Map res = (Map) com.mongodb.util.JSON.parse(postres);
                if ("200".equals(res.get("code").toString())) {
                    if (res.get("data") == null) {
                        return false;
                    }
                    Map<String, Object> articleData = (Map) res.get("data");
                    if (articleData != null) {
//                        if (articleData.containsKey("isDEL") && articleData.get("isDEL").toString().equals("1")) {
//                            return false;
//                        }
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                throw GlobalException.build("请求内容库失败");
            }
        } catch (Exception ex) {
            LOGGER.error("getNewsIsExit------------error", ex);
            throw GlobalException.build("请求内容库失败");
        }
    }


    /**
     * 获取steplink中使用过自定义菜单的token做推送条件
     * @return
     */
    public List<String> getPublicMenuTokens() {
        return publicMenuDao.getPublicMenuTokens();
    }
}
